package cn.witsky.rtp2ws.client.ws;

import java.net.URI;
import java.nio.ByteBuffer;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.framing.BinaryFrame;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.witsky.rtp2ws.domain.Rtp;
import cn.witsky.rtp2ws.util.LogUtil;
import net.sf.json.JSONObject;

public class WsClient extends WebSocketClient {
	private static Logger logger = LoggerFactory.getLogger(WsClient.class);
	private volatile boolean subscribe=true;	
	private ClientListener wsListener;

	static WsClient getWsClient(Rtp rtp,boolean retry) {
		String urlStr=ClientUtil.formatUrl(rtp, retry);
		URI uri = null;
		try {
			uri = new URI(urlStr);
		} catch (Exception e) {
			LogUtil.info(rtp,"WsClient[getWsClient:28]", "task:{}连接:{}",rtp.getRtpId(),urlStr);
		}
		logger.debug("connect ws uri:{}",uri);
		if(uri!=null) {
			WsClient client=new WsClient(uri);
			return client;
		}else {
			return null;
		}
	}
	public void sendBinary(byte[] bytes) {
	    BinaryFrame binaryFrame=new BinaryFrame();
	    binaryFrame.setPayload(ByteBuffer.wrap(bytes));
	    this.sendFrame(binaryFrame);
	}

	private WsClient(URI serverUri) {
		super(serverUri,new Draft_6455());
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onOpen(ServerHandshake handshakedata) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onMessage(String message) {
		// TODO Auto-generated method stub
		if(this.subscribe) {
			JSONObject jsonMsg=null;
			try {
				jsonMsg=net.sf.json.JSONObject.fromObject(message);
			}catch(Exception ex) {
				logger.error("接收到数据转换json异常,接收到的数据是:"+message, ex);
			}
			if(jsonMsg!=null) {
				if(this.wsListener!=null) {
					this.wsListener.onMessage(jsonMsg);
				}
			}
		}

	}

	@Override
	public void onClose(int code, String reason, boolean remote) {
		// TODO Auto-generated method stub
		if(this.subscribe) {
			if(this.wsListener!=null) {
				if(remote) {
					this.wsListener.onClose();
				}
			}
		}
	}

	@Override
	public void onError(Exception ex) {
		// TODO Auto-generated method stub
		
	}
	void addListener(ClientListener wsListener) {
		this.wsListener=wsListener;
	}
	
	ClientListener getWsListener() {
		return wsListener;
	}
	void setSubscribe(boolean subscribe) {
		this.subscribe = subscribe;
	}

}
